package com.le.tester.tip;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2022/2/11 17:00
 * description：reentrantLock dead lock
 */
public class ReentrantLockTester3 {

    static Lock lock1 = new ReentrantLock();
    static Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadDemo(lock1, lock2), "线程1");
        Thread t2 = new Thread(new ThreadDemo(lock1, lock2), "线程2");
        t1.start();
        t2.start();
        t1.interrupt();


    }

    static class ThreadDemo implements Runnable {

        Lock firstLock;
        Lock secondLock;

        public ThreadDemo(Lock firstLock, Lock secondLock) {
            this.firstLock = firstLock;
            this.secondLock = secondLock;
        }

        @Override
        public void run() {
            try {
                //尝试获取锁(不能设置尝试的时间)
//                firstLock.lockInterruptibly();
//                TimeUnit.MILLISECONDS.sleep(50);
//                secondLock.lockInterruptibly();
                lock1.tryLock(10, TimeUnit.MILLISECONDS);
                lock2.tryLock(10, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                //在线程获取到锁的时候，突然进行了中断。导致锁并没有释放
                firstLock.unlock();
                secondLock.unlock();
                System.out.println(Thread.currentThread().getName() + "获取到了资源，正常结束");
            }
        }
    }
}
